import axios from 'axios'
import store from '../store'
import router from '@/router'

const request = axios.create({
  baseURL: 'http://geek.itheima.net/v1_0/'
})

// 添加请求拦截器
request.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  if (store.state.user.token && config.url !== 'authorizations') {
    config.headers.Authorization = `Bearer ${store.state.user.token}`
  }
  return config
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})

// 添加响应拦截器
request.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  return {
    status: response.status,
    data: response.data.data
  }
}, async function (error) {
  // 对响应错误做点什么
  console.dir(error)
  const loginPath = `/login?redirectUrl=${router.currentRoute.path}`
  try {
    if (error.response?.status === 401) {
      const { user } = store.state
      if (!user.token || !user.refresh_token) {
        router.replace(loginPath)
        return Promise.reject(error)
      }
      const { data } = await request({
        url: 'authorizations',
        method: 'put',
        headers: {
          Authorization: 'Bearer ' + user.refresh_token
        }
      })
      store.commit('setToken', {
        token: data.token,
        refresh_token: user.refresh_token
      })
      return request(error.config)
    }
  } catch (error) {
    console.log(error)
    router.replace(loginPath)
    return Promise.reject(error)
  }
  return Promise.reject(error)
})

export default request
